package com.yy.glide;

import android.os.Build;
import android.util.LruCache;

import com.yy.glide.recycle.Resource;

public class LruMemoryCache extends LruCache<Key, Resource> implements MemoryCache {
    private ResourceRemoveListener mResourceRemoveListener;
    private boolean isRemoved;

    public LruMemoryCache(int maxSize) {
        super(maxSize);
    }

    @Override
    protected int sizeOf(Key key, Resource value) {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
            return value.getBitmap().getAllocationByteCount();
        }
        return value.getBitmap().getByteCount();
    }

    @Override
    protected void entryRemoved(boolean evicted, Key key, Resource oldValue, Resource newValue) {
        if (mResourceRemoveListener != null && oldValue != null && !isRemoved) {
            mResourceRemoveListener.onResourceRemove(oldValue);
        }
    }

    @Override
    public Resource removeResource(Key key) {
        isRemoved = true;
        Resource remove = remove(key);
        isRemoved = false;
        return remove;
    }

    @Override
    public void setResourceRemoveListener(ResourceRemoveListener listener) {
        this.mResourceRemoveListener = listener;
    }
}

